#include "pin_mux.h"
#include "clock_config.h"
#include "board.h"
#include "fsl_debug_console.h"
#include "fsl_gpio.h"
#include "cmsis_os.h"
#include "fsl_lpuart.h"
#include "sal_module_wrapper.h"
#include "ec600s.h"
#include "tos_at.h"
#include "mqttclient.h"
#include "cjson.h"
#include "sal_module_wrapper.h"

#define USE_ESP8266
//#define USE_EC600S

#if defined(USE_ESP8266)
#include "esp8266.h"
#elif defined(USE_EC600S)
#include "ec600s.h"
#endif

#ifdef USE_ESP8266 
static hal_uart_port_t esp8266_port = HAL_UART_PORT_2;

extern int person_flag;
extern int person_count;
extern int dagerous_flag;

void mqtt_set_esp8266_port(hal_uart_port_t port) {
    esp8266_port = port;
}
#endif

k_event_t report_result_event;
k_event_flag_t report_success = 1<<0;
k_event_flag_t report_fail    = 1<<1;

static void tos_topic_handler(void* client, message_data_t* msg)
{
    (void) client;
    cJSON* cjson_root   = NULL;
    cJSON* cjson_status = NULL;
    char* status = NULL;
    k_event_flag_t event_flag = report_fail;

    /* ��ӡ��־ */
    MQTT_LOG_I("-----------------------------------------------------------------------------------");
    MQTT_LOG_I("%s:%d %s()...\ntopic: %s, qos: %d. \nmessage:\n\t%s\n", __FILE__, __LINE__, __FUNCTION__, 
            msg->topic_name, msg->message->qos, (char*)msg->message->payload);
    MQTT_LOG_I("-----------------------------------------------------------------------------------\n");
    
    /* ʹ��cjson�����ϱ���Ӧ���� */
    cjson_root = cJSON_Parse((char*)msg->message->payload);
    if (cjson_root == NULL) {
    	MQTT_LOG_E("report reply message parser fail\r\n");
        event_flag = report_fail;
        goto exit;
    }
    
    /* ��ȡstatus״̬ */
    cjson_status = cJSON_GetObjectItem(cjson_root, "status");
    status = cJSON_GetStringValue(cjson_status);
    if (cjson_status == NULL || status == NULL) {
    	MQTT_LOG_E("report reply status parser fail\r\n");
        event_flag = report_fail;
        goto exit;
    }
    
    /* �ж�status״̬ */
    if (strstr(status,"success")) {
        event_flag = report_success;
    }else {
        event_flag = report_fail;
    }
    
exit:
    cJSON_Delete(cjson_root);
    cjson_root = NULL;
    status = NULL;
    
    //tos_event_post(&report_result_event, event_flag);
    
    return;
}


#define REPORT_DATA_TEMPLATE_COUNT "{\"method\":\"report\",\"clientToken\":\"00000001\",\"params\":{\"count\":%d}}"
#define REPORT_DATA_TEMPLATE_PERSON "{\"method\":\"report\",\"clientToken\":\"00000001\",\"params\":{\"person\":%d}}"
#define REPORT_DATA_TEMPLATE_WARNING "{\"method\":\"report\",\"clientToken\":\"00000001\",\"params\":{\"warning\":%d}}"
char report_buf[200];
static uint32_t send_count =0;
static uint8_t mqtt_avilid = 0;

void mqttclient_task_send_count(uint32_t count)
{
	k_event_flag_t event_flag = report_fail;

	if (mqtt_avilid)
	{
		send_count = count;
		tos_event_post(&report_result_event, event_flag);

	}
}

void mqttclient_task(void)
{
    int error;
    
    int lightness = 0;
    
    mqtt_client_t *client = NULL;
    
    mqtt_message_t msg;
    
    k_event_flag_t match_flag;
    
    char  host_ip[20];
    
    memset(&msg, 0, sizeof(msg));
    
#ifdef USE_ESP8266 
    esp8266_sal_init(esp8266_port);
    esp8266_join_ap("OnePlus7", "147258369");
#endif


#ifdef USE_EC600S
    ec600s_sal_init(HAL_UART_PORT_0);
#endif

    mqtt_log_init();

    client = mqtt_lease();
    
    tos_event_create(&report_result_event, (k_event_flag_t)0u);
    
    /* Domain Format: <your product ID>.iotcloud.tencentdevices.com */
    tos_sal_module_parse_domain("XXXXXXXXXX.iotcloud.tencentdevices.com",host_ip,sizeof(host_ip));
    
    /*
        These infomation is generated by mqtt_config_gen.py tool in "TencentOS-tiny\tools" directory.
    */
    mqtt_set_port(client, "1883");
    mqtt_set_host(client, host_ip);
    mqtt_set_client_id(client, "XXXXXXXXXXdev001");
    mqtt_set_user_name(client, "XXXXXXXXXXdev001;21010406;12365;4294967295");
    mqtt_set_password(client, "XXXXXXXXXXeb05cfea4e9daac571fb44f8a98b06;hmacsha1");
    mqtt_set_clean_session(client, 1);

    error = mqtt_connect(client);
    
    MQTT_LOG_D("\r\nmqtt connect error is %#0x", error);
    
    error = mqtt_subscribe(client, "$thing/down/property/XXXXXXXXXX/dev001", QOS0, tos_topic_handler);

    MQTT_LOG_D("mqtt subscribe error is %#0x", error);
    
    mqtt_avilid = 1;

    while (1) {

        memset(&msg, 0, sizeof(msg));
        snprintf(report_buf, sizeof(report_buf), REPORT_DATA_TEMPLATE_COUNT, person_count);
        msg.qos = QOS0;
        msg.payload = (void *) report_buf;
        error = mqtt_publish(client, "$thing/up/property/XXXXXXXXXX/dev001", &msg);
        MQTT_LOG_D("mqtt publish error is %#0x", error);
        

        memset(&msg, 0, sizeof(msg));
		snprintf(report_buf, sizeof(report_buf), REPORT_DATA_TEMPLATE_PERSON, person_flag);
		msg.qos = QOS0;
		msg.payload = (void *) report_buf;
		error = mqtt_publish(client, "$thing/up/property/XXXXXXXXXX/dev001", &msg);
		MQTT_LOG_D("\r\nmqtt publish error is %#0x", error);

        memset(&msg, 0, sizeof(msg));
		snprintf(report_buf, sizeof(report_buf), REPORT_DATA_TEMPLATE_WARNING, dagerous_flag);
		msg.qos = QOS0;
		msg.payload = (void *) report_buf;
		error = mqtt_publish(client, "$thing/up/property/XXXXXXXXXX/dev001", &msg);
		MQTT_LOG_D("\r\nmqtt publish error is %#0x", error);

        tos_task_delay(1500);
    }
}

void application_entry(void *arg)
{
	printf("enter application_entry\r\n");
    mqttclient_task();
    while (1) {
        printf("This is a mqtt demo!\r\n");
        tos_task_delay(1000);
    }
}
